package com.uff.hmstpa.vision.command;

import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JTextField;

import com.uff.hmstpa.model.domain.Doctor;
import com.uff.hmstpa.model.domain.Patient;

@SuppressWarnings("serial")
public class CreateAppointmentCommand extends AbstractViewCommand {

	JComboBox<Doctor> doctors;
	JComboBox<Patient> patient;
	JTextField date;
	JComboBox<String> time;
	JCheckBox homeride;

	public CreateAppointmentCommand(JComboBox<Doctor> doctorCB, JComboBox<Patient> patientCB, JTextField dateTF, JComboBox<String> timeCB, JCheckBox homerideCK) {
		this.doctors = doctorCB;
		this.patient = patientCB;
		this.date = dateTF;
		this.time = timeCB;
		this.homeride = homerideCK;
	}

	public void actionPerformed(ActionEvent evt) {
		String dName = doctors.getItemAt(doctors.getSelectedIndex()).getCRM();
		String patientName = patient.getItemAt(patient.getSelectedIndex()).getName();
		String patientCPF = patient.getItemAt(patient.getSelectedIndex()).getCpf();
		String sDate = date.getText();
		String sTime = time.getItemAt(time.getSelectedIndex());
		boolean isHomeride = homeride.isSelected();


		Map<String, Object> params = new HashMap<String, Object>();
		params.put("crm", dName);
		params.put("name", patientName);
		params.put("cpf", patientCPF);
		params.put("time", parseTime(sDate, sTime));
		params.put("homeride", isHomeride);

		controller.createAppointment(params);
	}

	private String parseTime(String unparsedDate, String unparsedTime) {
		try {
			String[] aux = unparsedTime.split(" - ");
			String parsedTime = aux[0].replace("h", ":00");

			String[] aux2 = unparsedDate.split("/");
			String parsedDate = aux2[2] + "-" + aux2[1] + "-" + aux2[0];

			return parsedDate + " " + parsedTime;
		} catch(ArrayIndexOutOfBoundsException e) {
			e.printStackTrace();
			return null;
		}
	}

}
